#include "StdAfx.h"

MovAvgCrossOver::MovAvgCrossOver(const vector<double>& _slowMA, const vector<double>& _fastMA, double stopLoss, double stopGain) : TradeSystem(stopLoss, stopGain)
{
	this->slowMA = _slowMA;
	this->fastMA = _fastMA;
}

MovAvgCrossOver::~MovAvgCrossOver(void) {}

bool MovAvgCrossOver::Buy(Quotation stockQuot, int i)
{
	//fastMA cross above slowMA
	if( (slowMA[i-1] != EMPTY && fastMA[i-1] != EMPTY) && (slowMA[i-1] >= fastMA[i-1]) && (fastMA[i] > slowMA[i]) ) 
	{
		this->_buyPrice = stockQuot.Prices[CLOSE];
		return true;
	}

	return false;
}

int MovAvgCrossOver::Sell(Quotation stockQuot, int i)
{
	double stopGainValue = ApplyStop(true, this->_buyPrice, stockQuot.Prices[HIGH]);
	double stopLossValue = ApplyStop(false, this->_buyPrice, stockQuot.Prices[LOW]);

	if( stopGainValue > 0 || stopLossValue > 0) {
		this->_sellPrice = (stopGainValue > 0) ? stopGainValue : stopLossValue;
		return -1;
	}
	else {
		if( (this->slowMA[i-1] <= this->fastMA[i-1]) && (this->fastMA[i] < this->slowMA[i]) ) {//fastMA cross below slowMA
			this->_sellPrice = stockQuot.Prices[CLOSE];
			return 1;
		}

		return 0;
	}
}

int MovAvgCrossOver::Cover(Quotation stockQuot, int i)
{
	double stopGainValue = ApplyStop(false, this->_shortPrice, stockQuot.Prices[LOW]);
	double stopLossValue = ApplyStop(true, this->_shortPrice, stockQuot.Prices[HIGH]);

	if( stopGainValue > 0 || stopLossValue > 0) {
		this->_coverPrice = (stopGainValue > 0) ? stopGainValue : stopLossValue;
		return -1;
	}
	else {
		if( (this->slowMA[i-1] >= this->fastMA[i-1]) && (this->fastMA[i] > this->slowMA[i]) ) {//fastMA cross above slowMA
			this->_coverPrice = stockQuot.Prices[CLOSE];
			return 1;
		}

		return 0;
	}
}

bool MovAvgCrossOver::Short(Quotation stockQuot, int i)
{
	//fastMA cross below slowMA
	if( (this->slowMA[i-1] <= this->fastMA[i-1]) && (this->fastMA[i] < this->slowMA[i]) ) {
		this->_shortPrice = stockQuot.Prices[CLOSE];
		return true;
	}

	return false;
}